package com.mzba.place.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.mzba.place.entity.LocationInfo;

/**
 * 位置信息表
 * @author 06peng
 *
 */
public class LocationInfoTable {

	public String TABLE_NAME = "locatoininfo_db";
	public static final String _id = "_id";
	public static final String key = "key";
	public static final String city = "city";
	
	private DBManagerImpl db = null;
	
	public LocationInfoTable(Context context) {
		if (db == null) {
			db = DBManager.get(context);
		}
		if (!db.isTableExits(db.getConnection(), TABLE_NAME)) {
			createTable();
		}
	}
	
	public LocationInfoTable() {
		
	}
	
	public void createTable() {
		String createTableSql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME
				+ "(_id integer primary key autoincrement, " + city + " VARCHAR,"  + key + "  VARCHARR)";
		db.creatTable(db.getConnection(), createTableSql, TABLE_NAME);
		
	}
	
	public void save(ArrayList<LocationInfo> list) {
		try {
			List<ContentValues> arraylist = new ArrayList<ContentValues>();
			db.delete(db.getConnection(), TABLE_NAME, null, null);
			for (LocationInfo info : list) {
				ContentValues values = new ContentValues();
				values.put(key, info.getKey());
				values.put(city, info.getCity());
				arraylist.add(values);
			}
			db.saveAll(db.getConnection(), TABLE_NAME, arraylist);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Cursor get() {
		Cursor cursor = db.find(db.getConnection(), "select * from " + TABLE_NAME, null);
		return cursor;
	}
	
	public void clearTable() {
		db.delete(db.getConnection(), TABLE_NAME, null, null);
	}
}
